package cn.newshasha.hlx.controller;

import cn.newshasha.hlx.model.Posts;
import cn.newshasha.hlx.model.WeChatTemplate;
import cn.newshasha.hlx.service.ToolsService;
import cn.newshasha.hlx.utils.HttpUtils;
import cn.newshasha.hlx.utils.WeChatUtils;
import com.alibaba.fastjson.JSON;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.log4j.Logger;
import org.jsoup.Connection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.*;

/**
 * @author bSu
 * @date 2021/1/31 - 17:50
 */
@RestController
public class WeChatController {

    private static Logger logger = Logger.getLogger(ToolsController.class);

    @Autowired
    private ToolsService toolsService;

    @Autowired
    private WeChatUtils weChatUtils;

    @Value("${weChat.tousers}")
    private String tousers;

    @Value("${weChat.template_id}")
    private String template_id;

    @Value("${weChat.url}")
    private String url;

    @Value("${weChat.sendTemplateUrl}")
    private String sendTemplateUrl;


    private static String getName(){
        return ToolsController.class.getName();
    }

    /**
     * WeChat接口校验
     * @param signature
     * @param timestamp
     * @param nonce
     * @param echostr
     * @return
     */
    @RequestMapping("/weChat")
    public Object weChat(String signature,String timestamp,String nonce,String echostr){
        System.out.println("请求成功");
        logger.info("signature:"+signature);
        logger.info("timestamp:"+timestamp);
        logger.info("nonce:"+nonce);
        logger.info("echostr:"+echostr);
        String token ="123123123";
        String tmpArr=token+timestamp+nonce;
        String s = DigestUtils.sha1Hex(tmpArr);
        logger.info("验证请求是否来自微信");
        logger.info("本地计算结果:"+s);
        if(s.equals(signature)){
            //验证成功
            return echostr;
        }
        return "";
    }

    //每天晚上23：30执行一次
    //@Scheduled(cron = "0 30 23 * * ?")
    @RequestMapping("/scheduled")
    public void pushDataScheduled() throws IOException {
        WeChatTemplate weChatTemplate = new WeChatTemplate();
        //提前组装非接收方信息
        //1、组装模板id
        weChatTemplate.setTemplate_id(template_id);
        weChatTemplate.setUrl(url);
        //3、组装data
        Map<Integer, Object> resultMap = (Map<Integer, Object>) toolsService.getRanking("96");
        Map<Integer, Object> ranking = new TreeMap<>(Collections.reverseOrder());
        ranking.putAll(resultMap);
        int i =1;//只要前十
        Map<String,Object> map = new LinkedHashMap<>();
        for(Integer integer : ranking.keySet()){
            String color = "#660000";
            if(i>1){
                color="##660000";//搞个错的就不带颜色
            }
            Map<String,Object> postMap = new HashMap<>();
            postMap.put("color",color);
            postMap.put("value",((Posts)ranking.get(integer)).getPostID());
            map.put("post"+i,postMap);
            Map<String,Object> titleMap = new HashMap<>();
            titleMap.put("color",color);
            titleMap.put("value",((Posts)ranking.get(integer)).getTitle());
            map.put("title"+i,titleMap);
            if(i>=10){
                break;
            }
            i++;
        }
        System.out.println(JSON.toJSON(map));
        weChatTemplate.setData(JSON.toJSON(map));
        //组装收信人
        String[] split = tousers.split(",");
        for(String wx : split){
            weChatTemplate.setTouser(wx);
            logger.info("发信报文："+ JSON.toJSON(weChatTemplate).toString());
            Connection.Response post = HttpUtils.post(sendTemplateUrl+weChatUtils.getAccess_token(), JSON.toJSON(weChatTemplate).toString());
            logger.info("发信结果："+post.body());
        }
    }

}
